package com.bmt.utils;

import java.util.Locale;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.LocaleUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.web.servlet.support.RequestContextUtils;

public final class Language_Utils {

	// HttpServletRequest req =
	// ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();

	public static void setLanguage(HttpServletRequest request, String language) throws Exception {
		Locale locale = StringUtils.isBlank(language) ? request.getLocale() : LocaleUtils.toLocale(language);

		String area = System_Utils.LANGUAGE_EN;
		if (Locale.CHINA.equals(locale)) {
			// 简体中文
			area = System_Utils.LANGUAGE_ZH;
			//暂时不支持繁体
			// } else if (Locale.CHINESE.equals(locale)) {
			// // 大陆地区以外,其它都视为繁体中文
			// area = System_Utils.LANGUAGE_HK;
			// locale = Locale.CHINESE;
		} else {
			// 中文以外,其它都视为英文
			area = System_Utils.LANGUAGE_EN;
			locale = Locale.ENGLISH;
		}
		request.getSession().setAttribute(System_Utils.SYS_LOCALE, locale);
		request.getSession().setAttribute(System_Utils.SYS_LOCALE_AREA, area);

	}

	public static String getMessage(HttpServletRequest request, String msgID) {
		return getMessage(request, msgID, null);
	}

	public static String getMessage(HttpServletRequest request, String msgID, Object[] arg) {
		Locale locale = getLocale(request);
		ApplicationContext ctx = RequestContextUtils.getWebApplicationContext(request);
		return ctx.getMessage(msgID, arg, locale);
	}

	private static Locale getLocale(HttpServletRequest request) {
		Locale locale = (Locale) request.getSession().getAttribute(System_Utils.SYS_LOCALE);
		if (locale == null) {
			return Locale.ENGLISH;
		}
		return locale;
	}

}
